using System;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

/// <summary>
/// 单独设置的目的是为了更好的拓展和处理不同的数据（如 HeightMap，MeshDatad等）
/// </summary>
public class ThreadedDataRequester : MonoBehaviour
{
    private static ThreadedDataRequester instance;
    private Queue<Threadinfo> dataQueue = new Queue<Threadinfo>();

    private void Awake()
    {
        if(instance==null)
            instance = FindObjectOfType<ThreadedDataRequester>();
    }

    /// <summary>
    /// 请求地图数据
    /// </summary>
    /// <param name="callBack"></param>
    public static void RequestData(Func<object> generateData ,Action<object> callBack)
    {
        ThreadStart threadStart = delegate {instance.DataThread(generateData,callBack);};
        
        new Thread(threadStart).Start();
    }

    void DataThread(Func<object> generateData,Action<object> callBack)
    {
        object data = generateData();
        lock (dataQueue)
        {
            dataQueue.Enqueue(new Threadinfo(callBack,data));
        }
    }
    
    private void Update()
    {
        if (dataQueue.Count > 0)
        {
            for (int i = 0; i < dataQueue.Count; i++)
            {
                Threadinfo threadinfo =  dataQueue.Dequeue();
                threadinfo.callback(threadinfo.parameter);
            }
        }
    }
    
    
    struct Threadinfo
    {
        public readonly Action<object> callback;
        public readonly object parameter;
        
        public Threadinfo(Action<object> callback, object parameter)
        {
            this.callback = callback;
            this.parameter = parameter;
        }
    }
}
